# encoding: utf-8
# Copyright 2011, Google Inc. All Rights Reserved.

"""Sample live stream gadget
"""

__author__ = 'lbayliss@google.com (Leon Bayliss)'

import os, logging
from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

# import common methods, classes
from py.common import blockstore
cache = blockstore.BlockStore("rhl")

# determine path to block default HTML files
blockPath = os.path.join(os.path.dirname(__file__), '..', 'block')

# web handlers
class GetStateHash(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = "application/x-javascript"
		self.response.headers.add_header("Pragma","no-cache")
		self.response.headers.add_header("Cache-Control","no-cache")
		self.response.out.write(json.dumps(dict(cache.state)))
		self.response.out.write("\r\n")

class GetBlockHash(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = "application/x-javascript"
		self.response.headers.add_header("Pragma","no-cache")
		self.response.headers.add_header("Cache-Control","no-cache")
		self.response.out.write(json.dumps(dict(cache.blocks)))
		self.response.out.write("\r\n")

class GetState(webapp.RequestHandler):
	def get(self,name):
		self.response.headers['Content-Type'] = "application/x-javascript"
		self.response.headers.add_header("Pragma","no-cache")
		self.response.headers.add_header("Cache-Control","no-cache")
		self.response.out.write(json.dumps(cache.state[name]))
		self.response.out.write("\r\n")

class SetState(webapp.RequestHandler):
	def get(self,name,value):
		cache.setstate(name,int(value))
		self.response.headers['Content-Type'] = "application/x-javascript"
		self.response.headers.add_header("Pragma","no-cache")
		self.response.headers.add_header("Cache-Control","no-cache")
		self.response.out.write(json.dumps(cache.state[name]))
		self.response.out.write("\r\n")

class Reset(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = "application/x-javascript"
		cache.reset()
		self.response.out.write(json.dumps(dict(cache.state)))
		self.response.out.write("\r\n")

class BlockStatic(webapp.RequestHandler):
	def get(self,name):
		html = cache[name]
		if html==None:
			logging.warn("Block does not exist, '%s'" % name)
			path = os.path.join(blockPath,'%s.html' % name)
			if os.path.exists(path):
				logging.debug("Storing block '%s' from file: %s" % (name,path))
				html = cache.fromfile(name,path)
			else:
				logging.error("Path not found: %s" % path)
				self.error(404)
		if html:
			self.response.headers['Content-Type'] = "text/html"
			self.response.headers.add_header("Pragma","no-cache")
			self.response.headers.add_header("Cache-Control","no-cache")
			self.response.out.write(html)
			self.response.out.write("\r\n")
		else:
			self.error(404)

class GetSetBlock(webapp.RequestHandler):
	def get(self,name,state):
		self.response.headers['Content-Type'] = "application/x-javascript"
		self.response.out.write(json.dumps(cache.getblock(name,int(state))))
		self.response.out.write("\r\n")		
	def post(self,name,state):
		self.response.headers['Content-Type'] = "text/html"
		cache.setblock(name,int(state),self.request.body)
		self.response.out.write(json.dumps(cache.getblock(name,int(state))))
		self.response.out.write("\r\n")

debug = True
application = webapp.WSGIApplication([
		(r'/state/reset', Reset),
		(r'/state/(\w+)', GetState),
		(r'/state/(\w+)\/(\d+)', SetState),
		(r'/block/(\w+)\/(\d+)', GetSetBlock),
		(r'/state.js',GetStateHash),
		(r'/blocks.js',GetBlockHash),
		(r'/b/(\w+)\.html', BlockStatic)
	],debug=debug)

def main():
	if debug:
		logging.getLogger().setLevel(logging.DEBUG)
	run_wsgi_app(application)

if __name__ == "__main__":
  main()
